<template>
  <div class="component-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      fixed
      placeholder 
      class="top-nav-bar"
      @click-right="$router.push({name: 'home'})"
      @click-left="$router.back()"
    >
      <template #left>
        <div class="top-nav-bar-left">
          <van-icon name="arrow-left" color="#000" class="icon"/>
        </div>
      </template>
      <template #right>
        <div class="top-nav-bar-left-img-box">
          <img src="@/assets/meiuo-logo.png" alt="">
        </div>
      </template>
    </van-nav-bar>
    <!-- 顶部标签页 -->
    <van-sticky :offset-top="50">
      <van-tabs v-model="active">
        <van-tab title="宝贝"></van-tab>
        <!-- <van-tab title="评论"></van-tab> -->
      </van-tabs>
    </van-sticky>
    <!-- 商品详细信息展示区域 -->
    <div class="goods-detail-container">
      <!-- 图片轮播区域 -->
      <van-swipe @change="onChange" :autoplay="3000" class="swipe">
        <van-swipe-item v-for="goodsPic in goodsDeatilInfo.goodsPicturePath" :key="goodsPic">
          <div class="goods-img-box">
            <img :src="goodsConstants.goodsPictureBaseURL + goodsPic" alt="">
          </div>
        </van-swipe-item>
        <template #indicator>
          <div class="custom-indicator">{{ current + 1 }}/{{goodsPictureCount}}</div>
        </template>
      </van-swipe>
      <!-- 商品信息 -->
      <div class="goods-info">
        <div class="goods-price">
          <span>￥</span>
          <span>{{goodsPrice.split('.')[0]}}</span>
          <span>.</span>
          <span>{{goodsPrice.split('.')[1]}}</span>
        </div>
        <div class="goods-name">
          <span>{{goodsDeatilInfo.goodsName}}</span>
        </div>
        <div class="goods-other-info">
          <span>销售量: {{goodsDeatilInfo.goodsSaleNumber}}</span>
          <span>运费: {{goodsDeatilInfo.goodsFreight}}</span>
          <span>评论数: {{goodsDeatilInfo.goodsCommentNumber}}</span>
        </div>
      </div>
    </div>
    <!-- 商品参数选择 -->
    <van-action-sheet v-model="show">
      <div class="param-select-container">
        <!-- 商品信息 -->
        <div class="goods">
          <div class="goods-img">
            <img :src="goodsConstants.goodsPictureBaseURL + goodsDeatilInfo.goodsPicturePath[0]" alt="">
          </div>
          <div class="goods-price">
            <span>￥</span>
            <span>{{goodsPrice}}</span>
          </div>
          <!-- 关闭图标 -->
          <div class="close">
            <van-icon name="close" @click="show=false"/>
          </div>
        </div>
        <!-- 商品参数信息 -->
        <div class="param-group" v-for="(paramGroup, index) in goodsParams" :key="index">
          <div>{{index}}</div>
          <span 
            v-for="param in paramGroup" 
            :key="param" 
            @click="select(index, param)" 
            :class="param == selectParam[index] ? 'selected' : ''"
          >{{param}}</span>
        </div>
        <!-- 购买数量 -->
        <div class="pay-number">
          <span>购买数量</span>
          <div class="stepper">
            <van-stepper v-model="selectNumber" theme="round" button-size="22" disable-input />
          </div>
        </div>
        <!-- 按钮 -->
        <van-button type="danger" class="btn" @click="confirm">确认</van-button>
      </div>
    </van-action-sheet>
    <!-- 底部商品导航 -->
    <van-goods-action style="z-index: 102;">
      <van-goods-action-icon icon="cart-o" text="购物车" :to="{name: 'cart'}"/>
      <van-goods-action-button type="warning" text="加入购物车" @click="show = true; isPay=false"/>
      <van-goods-action-button type="danger" text="立即购买" @click="show = true; isPay=true"/>
    </van-goods-action>
  </div>
</template>

<script>
import { Swipe, SwipeItem } from 'vant'
import { Tab, Tabs, Sticky, ActionSheet } from 'vant'
import { GoodsAction, GoodsActionIcon, GoodsActionButton } from 'vant'
import { Stepper } from 'vant'

export default {
  name: 'GoodsDetail',
  components: {
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [Tab.name]: Tab,
    [Sticky.name]: Sticky,
    [Tabs.name]: Tabs,
    [GoodsAction.name]: GoodsAction,
    [GoodsActionIcon.name]: GoodsActionIcon,
    [GoodsActionButton.name]: GoodsActionButton,
    [ActionSheet.name]: ActionSheet,
    [Stepper.name]: Stepper,
  },
  data() {
    return {
      goodsId: 0,
      active: 0,  // 选择哪个标签页面
      current: 0, // 轮播图当前第几张图片
      show: false, // 是否展示商品参数选择
      goodsDeatilInfo: {},
      goodsPictureCount: 0,
      goodsPrice: '',
      goodsParams: {},
      selectParam: {},
      paramArray: [], // 商品参数数组
      selectNumber: 0, // 当前商品选择的数量
      isPay: false, // 是否直接购买
    }
  },
  methods: {
    onChange(index) {
      this.current = index;
    },
    // 商品参数选择
    select(paramGroup, param) {
      this.selectParam[paramGroup] = param
      // console.log(param == this.selectParam[paramGroup])
    },
    // 确认选择的商品参数
    confirm() {
      // 检验是否选择了，检验是否可以提交信息
      let isSubmit = true
      this.paramArray.forEach(item=>{
        // console.log(this.selectParam[item])
        if (this.selectParam[item].length === 0) {
          this.$toast.fail('请选择商品参数')
          isSubmit = false
        }
      })
      if (!isSubmit) return 
      // 检验用户是否登录
      let isLogin = true
      this.req.get(
        'user/login/',
        {
          params: {
            token: localStorage.getItem('token')
          }
        }
      ).then((res) => {
        // console.log(res.data)
        if (res.data.mark === 1) {
          isLogin = true
        } else {
          this.$toast.fail(res.data.message)
          this.$router.push({name: 'login'})
          isLogin = false
        }
      }, err => {
        isLogin = false
        Toast.fail(err)
      })
      if (!isLogin) return 
      // 判断是加入购物车还是立即购买
      if (this.isPay) { // 立即购买
        // 加入购物车 
        this.req.post(
          'user/add/userCartInfo/',
          {
            token: localStorage.getItem('token'),
            goodsId: this.goodsId,
            selectParam: this.selectParam,
            selectNumber: this.selectNumber
          }
        ).then(res=>{
          let data = res.data
          if (data.mark === 1) {
            this.$toast.success(data.message)
            this.show = false // 关闭商品参数选择
            // 
            this.req.post(
              'user/get/new/userCartInfo/id/',
              {
                token: localStorage.getItem('token')
              }
            ).then(res=> {
              if (res.data.mark === 1) {
                this.$router.push({
                  name: 'submitOrder',
                  query: {
                    goodsIds: [res.data.data]
                  }
                })
              } else {
                this.$toast.fail(res.data.message)
              }
            }, err=>{
              this.$toast.fail(err)
            })
          } else {
            this.$toast.fail(data.message)
          }
        }, err=>{
          this.$toast.fail(err)
        })
      } else {
        this.req.post(
          'user/add/userCartInfo/',
          {
            token: localStorage.getItem('token'),
            goodsId: this.goodsId,
            selectParam: this.selectParam,
            selectNumber: this.selectNumber
          }
        ).then(res=>{
          let data = res.data
          if (data.mark === 1) {
            this.$toast.success(data.message)
            this.show = false // 关闭商品参数选择
          } else {
            this.$toast.fail(data.message)
          }
        }, err=>{
          this.$toast.fail(err)
        })
      }
    },
  },
  created() {
    this.goodsId = this.$route.query.goodsId // 获取当前页面商品id
    // 获取该商品的详细信息
    this.req.get(
      'goods/goodsDetail/',
      {
        params: {
          goodsId: this.goodsId
        }
      }
    ).then(res=>{
      let data = res.data
      if (data.mark == 1) {
        this.goodsDeatilInfo = data.data
        this.goodsPictureCount = data.data.goodsPicturePath.length // 商品图片个数
        this.goodsPrice = data.data.goodsPrice
        // 处理商品参数
        let goodsParams = data.data.goodsParams
        let paramCategory = []
        for (let i=0; i<goodsParams.length; i++) {
          paramCategory.push(goodsParams[i][0])
        }
        paramCategory = new Set(paramCategory)
        let params = {}
        paramCategory.forEach(item=>{
          this.paramArray.push(item)
          let arr = []
          goodsParams.forEach(i=>{
            if (i[0] === item) {
              arr.push(i[1])
            }
          })
          params[item] = arr
          // this.selectParam[item] = ''
          // 向对象添加属性，并使其被vue代理
          // 对象名，属性，属性值
          this.$set(this.selectParam, item, '')
        })
        this.goodsParams = params
      } else {
        this.$toast.fail(data.message)
      }
    }, err=>{
      this.$toast.fail(err)
    })
  }
}
</script>

<style lang="less" scoped>
// 顶部导航栏样式
.top-nav-bar-left {
  .icon {
    vertical-align: baseline;
    font-size: 1.8rem;
  }
}
.top-nav-bar-left-img-box {
  height: 35px;
  visibility: middle;
}
// 轮播图样式
.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 5px;
  padding: 2px 5px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
}
// 商品展示图片样式
.goods-img-box {
  margin: 0.05rem 0 0 0;
  height: 26rem;
  img {
    display: block;
    height: 100%;
    margin: 0 auto;
  }
}
// 商品信息样式
.goods-info {
  box-sizing: border-box;
  width: 98%;
  margin: 0.5rem auto;
  padding: 0.9rem;
  background-color: #fff;
  border-radius: 1rem;
  .goods-price {
    // margin: 0 0 0.4rem 0;
    color: #ee0a24;
    span:nth-child(1) {
      font-size: 1rem;
    }
    span:nth-child(2) {
      font-size: 1.6rem;
    }
  }
  .goods-name {
    margin: 0.9rem 0;
    span {
      font-size: 1.1rem;
      font-weight: 600;
    }
  }
  .goods-other-info {
    margin: 1.2rem 0 0;
    display: flex;
    justify-content: space-between;
    span {
      font-size: 0.9rem;
      color: #888;
    }
  }
}
// 商品参数选择样式
.content {
  padding: 16px 16px 160px;
}
// 商品参数选择容器
.param-select-container {
  position: relative;
  // height: 40rem;
  padding: 1rem;
  // 有关商品信息样式
  .goods {
    position: relative;
    padding: 0 0 0.7rem 0;
    border-bottom: 1px solid #eee;
    .goods-img {
      display: inline-block;
      overflow: hidden;
      height: 6rem;
      width: 6rem;
      border-radius: 1rem;
      img {
        width: 100%;
      }
    }
    .goods-price {
      position: absolute;
      top: 0.6rem;
      left: 6.8rem;
      color: #ee0a24;
      span:nth-child(2) {
        font-size: 1.5rem;
      }
    }
    .close {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 1.5rem;
    }
  }
  // 商品参数样式
  .param-group {
    padding: 1rem 0;
    border-bottom: 1px solid #eee;
    span {
      display: inline-block;
      // box-sizing: border-box;
      padding: 0.2rem 0.5rem;
      margin: 0.7rem 1rem 0 0;
      min-width: 3rem;
      background-color: #eee;
      border-radius: 0.5rem;
      text-align: center;
    }
    .selected {
      border: 1px solid #ee0a24;
      background-color: #fff;
      color: #ee0a24;
    }
  }
  // 购买数量
  .pay-number {
    height: 2rem;
    padding: 1rem 0;
    border-bottom: 1px solid #eee;
    line-height: 2rem;
    span {
      float: left;
    }
    div {
      float: right;
    }
  }
  // 按钮
  .btn {
    // position: absolute;
    // bottom: 0rem;
    width: 100%;
    margin: 1.5rem 0 0 0;
    border-radius: 2rem;
  }
}
</style>